<template>
  <div class="font12 clearfix multi-label clear-wrap">
    <div class="zhezhao" :class="checkMultiLabel?'show-zhezhao':'hide-zhezhao'" v-show="flag === 'QC'"></div>
    <div class="box-wrap"  :class="flag === 'QC'?'QC-label-select':''" >
      <span class="label-title" v-show="!isDialog">{{$t('public.callLabel')}}：</span>
      <div class="label-right" :class="isDialog?'phoneBar-padding':''" v-if="callLabel.multiLabels && callLabel.multiLabels.length <=0">{{$t('call.noCallLabel')}}</div>
      <div class="label-right" :class="isDialog?'phoneBar-padding':''" v-else>
        <ul class="clearfix" v-show="!loading">
          <!--是单击标签并且不是停用的标签-->
          <li v-for="(item, index) in newCheckLabels" :key="index"  class="label-clear" v-if="item.indexOf('@') <= -1 && getSingleName(item)">
            <label class="label-box">
              <input type="checkbox" checked disabled="disabled" :value="item" :title="getSingleName(item)"><span class="label-text label-cursor">{{getSingleName(item)}}</span>
            </label>
          </li>
        </ul>
        <ul class="ul-name clearfix" v-show="!loading">
          <!--是多级标签并且不是停用的标签-->
          <li v-for ='(item, index) in newCheckLabels' :key="index" v-if="item.indexOf('@') > -1 && trunLableNameById(item)"><span class="label-span label-cursor" :title="trunLableNameById(item)">{{trunLableNameById(item)}}</span><p v-show= "showAdd" @click="removeMultiLabel(item)">X</p></li>
        </ul>
        <div :class="{'clearfix':clearFix,'has-single':flagSing}">
          <span  v-show= "showAdd">
             <el-cascader
               v-if="getLabelLength > 5000"
               popper-class="multi-cascader"
               :options="callLabel.multiLabels || []"
               v-model="selectedOptions"
               @change="handleChange"
               size="mini"
               separator=">"
               filterable
               :props="labelProps"
              >
              </el-cascader>
               <el-cascader
               v-else
               popper-class="multi-cascader"
               :options="callLabel.multiLabels || []"
               v-model="selectedOptions"
               @change="handleChange"
               size="mini"
               separator=">"
               filterable
              >
              </el-cascader>
          </span>
          <div class="btn-group fr">
            <el-button style="min-width:10px;" :disabled="disabled" type="primary" class="add-label-btn fl primary_btn" size="small" v-show="showAdd" @click.stop="addMultiCallLabel(false)">{{$t('public.add')}}</el-button>
            <el-button style="min-width:10px;" v-show="showOperaLog" :class="getTabType === 'cdr_all'?'opera-left': ''" class="fr primary_btn rest-btn" size="small" @click.stop="checkOperationLog">{{$t('call.checkOperate')}}</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :title="$t('public.changeLog')" :visible.sync="checkOpearaDialog" class='call-label-dialog'>
      <div v-if="operaHistory&&operaHistory.length<=0" class="no-opera">{{$t('call.noOperate')}}</div>
      <operation-log v-else :labelOperaHistory = 'operaHistory'></operation-log>
    </el-dialog>
    <el-dialog :title="$t('public.tip')" append-to-body modal-append-to-body :visible.sync="checkMultiLabel" :show-close="false" :modal="flag==='QC'?false:true">
      <span>{{$t('call.replaceSingleLabel')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="checkMultiLabel=false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="addMultiCallLabel(true)">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  // 此组件是多级标签组件，此组件还涉及有单标签旧数据替换成多标签的情况
  import { getSingleOrMultiLabelNameById, getCache } from '@/utils/m7Utils.js'
  import OperationLog from '@/components/public-modules/cust-tab-content/operation-log/'
  export default {
    name: 'MultiLabel',
    data () {
      return {
        selectedOptions: [], // 标签树形选中的值
        currentCheckOptions: [], // 当前change操作的数据
        loading: true,
        flagSing: true, // 是否有单标签的标志，这个应该和hasSingle重复了
        clearFix: true,
        newCheckLabels: this.checkLabels, // 解决标签覆盖之后，再change服务质量标签导致覆盖失败的问题
        operaHistory: [], // 操作日志
        checkOpearaDialog: false, // 操作日志的弹窗
        hasSingle: false, // 是否有单标签的标志
        checkMultiLabel: false, // 是否要覆盖单标签的弹窗
        labelProps: {
          lazy: true,
          lazyLoad (node, resolve) {
            setTimeout(() => {
              // 通过调用resolve将子节点数据返回，通知组件数据加载完成
              resolve()
            }, 50);
          }
        }
      }
    },
    props: {
      callLabel: Object, // 所有的标签
      checkLabels: Array || [], // 当前选中的标签
      callSheetId: String, // 通话id
      disabled: {type: Boolean, default: false}, // 是否可点击
      flag: String, // 判断模块的标志 eg: QC
      phoneBarFlag: Boolean, // 是否是电话条
      refreshCallLabel: Number, // 点击质检评分的时候重新rest
      // agentId: String,
      showAdd: {type: Boolean, default: false}, // 控制添加按钮是否显示
      showOperaLog: {type: Boolean, default: false}, // 控制操作日志按钮是否显示
      isDialog: {type: Boolean, default: false} // 是否是弹窗类型的，弹窗类型的样式要做调整
    },
    watch: {
      refreshCallLabel: 'refreshCallLabeles'
    },
    computed: {
      isCalling () {
        return this.$store.state.cti.globalLet.isLabelShow
      },
      getLabelLength () {
        return  Object.keys(this.$store.state.allKeyLabels || {}).length
      }
    },
    methods: {
      getTabType () { // 获取tabType eg： cdr_my, cdr_all
        let routeArry = this.$route.path.split('/')
        let tabType = routeArry[3]
        return tabType || ''
      },
      getServerUrl () { // 获取当前坐席所在的pbx
        let pbxid = this.$store.state.session.user.pbx
        let curpbx = ''
        let assDomain = ''
        if (pbxid) {
          curpbx = getCache('accountPbx', pbxid)
          assDomain = curpbx.assAddr
        }
        return assDomain
      },
      handleChange (value) { // change树形
        this.currentCheckOptions = value || []
      },
      refreshCallLabeles () {
        this.newCheckLabels = this.checkLabels
        if (this.refreshCallLabel) { // 点击质检评分界面的时候，重新reset
          // this.restSelect()
          this.currentCheckOptions = []
          this.selectedOptions = []
        }
        if (this.newCheckLabels.length <= 0) {
          this.flagSing = false
        } else {
          this.flagSing = true
        }
      },
      getRecoverName (arr) { // 获取被覆盖标签名字
        let nameStr = ''
        for (let m = 0; m < arr.length; m++) {
          nameStr += arr[m] + '、'
        }
        return nameStr.substring(0, nameStr.length - 1)
      },
      getSingleName (id) { // 获取单标签名字
        if (!id) {
          return ''
        }
        let single = this.$store.state.call.transCache.singleLabel
        let allSingle = ''
        if (single) {
          this.hasSingle = true // 有之前打过的单击标签
          allSingle = single.singleLabel
        }
        return getSingleOrMultiLabelNameById(allSingle, id)
      },
      trunLableNameById (item) { // 通话标签id来匹配标签名字
        if (!item) {
          return ''
        }
        let usedLabel = []
        if (item.indexOf('@') !== -1) { // 判断是不是多级
          usedLabel = item.split('@') // @1@2@3拆分为数组
          usedLabel.pop()
        }
        let labelName = ''
        const allKeyLabels = this.$store.state.allKeyLabels || {}
        for (let j = 0; j < usedLabel.length; j++) {
          const labelStr = allKeyLabels !== {} ? allKeyLabels[usedLabel[j]] : ''
          if (labelStr) {
            labelName += labelStr + '>'
          }
        }
        labelName = labelName.substring(0, labelName.length - 1)
        this.hasSingle = false
        return labelName
      },
      addMultiCallLabel (flag) { // 添加多级标签 flag为true 表示是提示框中的确定按钮触发的事件
        let sameFlag = false
        let labelIdList = ''
        let lastLabelNameStr = ''
        let lastLabelName = []
        let opArr = []
        if (!this.currentCheckOptions || this.currentCheckOptions.length <= 0) {
          this.$message.error(this.$t('call.pleaceChoiseFirstLabel'))
          return false
        }
        for (let i = 0; i < this.currentCheckOptions.length; i++) {
          labelIdList += this.currentCheckOptions[i]._id + '@'
          if (i === this.currentCheckOptions.length - 1) {
            lastLabelNameStr += this.currentCheckOptions[i].name
          } else {
            lastLabelNameStr += this.currentCheckOptions[i].name + '>'
          }
        }
        lastLabelName = lastLabelNameStr ? [lastLabelNameStr] : []
        if (this.newCheckLabels) {
          this.flagSing = true
          this.newCheckLabels.forEach(item => {
            if (this.isCallingJudge()) { // 软电话
              if (item.replace('##', '') === labelIdList) { // 标签重复时
                sameFlag = true
              }
              this.newCheckLabels[item] = this.newCheckLabels[item] + '##'
            } else {
              if (item === labelIdList || item.replace('##', '') === labelIdList) {
                sameFlag = true
              }
            }
          })
        }
        if (sameFlag) {
          this.$message.error(this.$t('call.labelSameWarn'))
          return
        }
        if (this.hasSingle && !flag) { // 之前有打过单标签并且不是软电话状态
          this.checkMultiLabel = true
          return
        }
        if (flag) {
          this.checkMultiLabel = false
          this.hasSingle = false
          this.newCheckLabels = [] // 要把之前选中的单标签清空
        }
        if (this.isCallingJudge()) {
          this.newCheckLabels.push(labelIdList + '##')
        } else {
          this.newCheckLabels.push(labelIdList)
        }
        opArr.push(labelIdList)
        if (this.isCallingJudge()) { // 通话中 && (卡片中点开的是当前通话的id || 电话条)
          this.callingToRecod(opArr, lastLabelName)
        } else {
          this.calledToRecord(opArr, lastLabelName, flag)
        }
      },
      isCallingJudge () {
        return this.isCalling && (this.callSheetId === this.$store.state.cti.globalLet.currentCallSheetId || this.phoneBarFlag)
      },
      callingToRecod (opArr, lastLabelName) {
        let phoneData = this.$store.state.cti.globalLet.phone_data
        let phoneBarData = {
          Channel: phoneData._curChannel,
          pbx: phoneData.pbx_in_ip,
          operation: 'add',
          label_op: opArr,
          url: this.getServerUrl,
          callSheetId: this.$store.state.cti.globalLet.currentCallSheetId,
          value: 'LABELS' + this.newCheckLabels,
          name: lastLabelName
        }
        phoneBarData.value = phoneBarData.value.replace(/,/g, '')
        this.$store.dispatch('markCallSheetThroughCall', phoneBarData).then((resp) => {
          this.selectedOptions = []
          let labelIdObj = {
            callId: phoneBarData.callSheetId,
            labelIdArray: this.newCheckLabels
          }
          this.commitLabelsUpdate(this.newCheckLabels)
          window.localStorage.setItem('labelIdObj', JSON.stringify(labelIdObj))
        })
      },
      calledToRecord (opArr, lastLabelName, flag) {
        let state = {}
        state.label = this.newCheckLabels.filter(item => {
          if (item) {
            return item
          }
        })
        if (state.label && state.label.length === 0) {
          return
        }
        state.callSheetId = this.callSheetId
        state.operation = 'add'
        if (flag) {
          state.operation = 'recover'
        }
        state.label_op = opArr
        state.name = lastLabelName
        let lastData = {data: state, type: this.getTabType}
        if (this.flag === 'QC') { // QC && UNDEAL 质检和通话待处理的打标签去掉处理坐席验证，即：处理坐席不是自己也可以打标签
          delete lastData.type
          lastData.data.flag = 'QC'
          this.$store.commit('singleLabelChange/qualityCheck')
        } else if (this.flag === 'UNDEAL') {
          lastData.data.flag = 'UNDEAL'
        }
        this.$store.dispatch('markCallSheet', lastData).then((resp) => {
          if (resp) {
            this.selectedOptions = []
            this.commitLabelsUpdate(state.label )
          } else {
            this.newCheckLabels = []
            this.$message.error(this.$t('call.addLabelFail'))
          }
        })
      },
      commitLabelsUpdate (opArr) {
        this.$store.commit('call/COMMENTS', {id: this.callSheetId, labels: opArr, tabType: 'cdr_call'})
        this.$store.commit('call/COMMENTS', {id: this.callSheetId, labels: opArr, tabType: 'cdr_outbound'})
        this.$store.commit('call/COMMENTS', {id: this.callSheetId, labels: opArr, tabType: 'cdr_pending'})
        this.$store.commit('call/COMMENTS', {id: this.callSheetId, labels: opArr, tabType: 'cdr_all'})
      },
      removeMultiLabel (id) { // 删除多级标签
        let arr = this.newCheckLabels
        let opArr = []
        let nameArr = []
        opArr.push(id)
        for (let j = 0; j < arr.length; j++) {
          if (arr[j] === id) {
            arr.splice(j, 1)
          }
        }
        if (this.newCheckLabels.length <= 0) {
          this.flagSing = false
        }
        this.newCheckLabels = arr
        let name = this.trunLableNameById(id)
        nameArr.push(name)
        if (this.isCallingJudge()) { // 通话中 && (卡片中点开的是当前通话的id || 电话条)
          this.callingToRemove(opArr, nameArr)
        } else {
          this.calledToRemove(opArr, nameArr)
        }
      },
      callingToRemove (opArr, nameArr) {
        let phoneData = this.$store.state.cti.globalLet.phone_data
        let phoneBarData = {
          Channel: phoneData._curChannel,
          pbx: phoneData.pbx_in_ip,
          operation: 'delete',
          label_op: opArr,
          url: this.getServerUrl,
          callSheetId: this.$store.state.cti.globalLet.currentCallSheetId,
          value: 'LABELS' + this.newCheckLabels,
          name: nameArr
        }
        phoneBarData.value = phoneBarData.value.replace(/,/g, '')
        this.$store.dispatch('markCallSheetThroughCall', phoneBarData).then((resp) => {
          if (resp.success) {
            this.$message({
              message: this.$t('sms.successDel'),
              type: 'success'
            })
            let labelIdObj = {
              callId: phoneBarData.callSheetId,
              labelIdArray: this.newCheckLabels
            }
            this.commitLabelsUpdate(this.newCheckLabels)
            window.localStorage.setItem('labelIdObj', JSON.stringify(labelIdObj))
          } else {
            this.$message.error(this.$t('sms.failDel'))
          }
        })
      },
      calledToRemove (opArr, nameArr) {
        let state = {}
        state.label = this.newCheckLabels
        state.callSheetId = this.callSheetId
        state.operation = 'delete'
        state.label_op = opArr
        state.name = nameArr
        let lastData = {data: state, type: this.getTabType}
        if (this.flag === 'QC') { // QC && UNDEAL 质检和通话待处理的打标签去掉处理坐席验证，即：处理坐席不是自己也可以打标签
          delete lastData.type
          lastData.data.flag = 'QC'
          this.$store.commit('singleLabelChange/qualityCheck')
        } else if (this.flag === 'UNDEAL') {
          lastData.data.flag = 'UNDEAL'
        }
        this.$store.dispatch('markCallSheet', lastData).then((resp) => {
          if (resp) {
            this.$message({
              message: this.$t('sms.successDel'),
              type: 'success'
            })
            this.commitLabelsUpdate(state.label)
          } else {
            this.$message.error(this.$t('sms.failDel'))
          }
        })
      },
      checkOperationLog () { // 查询通话标签的操作日志
        let lastData = {data: {callSheetId: this.callSheetId}, type: this.getTabType}
        this.$store.dispatch('getCallLabelOPHistory', lastData).then((resp) => {
          if (resp.success) {
            let list = resp.history.reverse()
            this.operaHistory = list
            this.checkOpearaDialog = true
          } else {
            this.$message.error(this.$t('call.getOperateFail'))
          }
        })
      }
    },
    components: {
      OperationLog
    },
    mounted () {
      setTimeout(() => { // 为了解决第一次加载这个组件时，props没有把最新数据传下来的问题
        this.newCheckLabels = this.checkLabels
        this.loading = false
      }, 1000)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .multi-label
    .bet-line
      &:before
        content: ''
        display inline-block
        width 15px
        height 1px
        margin 3px 6px 3px 2px
        background $cf-level2
        text-align center
    .box-wrap
      position relative
      .label-title
        width 6em
        position absolute
        top 0
        left 0
      .label-right
        margin-left 6em
      .phoneBar-padding
        margin-left 0
        margin-top 10px
    .el-dialog__header
      border-bottom 1px solid #d3d3d3
      padding 16px
    .label-select
      padding-right 10px
      width 18%
      font-size 12px
    .el-cascader
      width 60%
    .QC-label-select
      .label-select
        width 100%
        margin-bottom 16px
        padding-right 0
      .label-right
        margin-left 100px
      .label-title
        width 100px
      .has-single
        border-top 0
        padding-top 0
      li span.label-span
        max-width 20em
      .el-cascader
        width 100%
      .add-label-btn
        margin-top 16px
      .label-title
        padding-top 10px
    .btn-group
      .opera-left
        float left
    .ul-name
      li
        position relative
        min-width 6em
        height 26px
        line-height 26px
        max-width 36em
        float left
        margin 0px 20px 16px 0
        .label-span
          border 1px solid $c-border2
          min-width 6em
          height 26px
          box-sizing border-box
          line-height 26px
          max-width 35em
          display block
          border-radius 3px
          text-align center
          float left
          padding 0 10px
          text-overflow ellipsis
          overflow hidden
          white-space nowrap
        p
          display none
      li:hover
        p
          display block
          color $cf-white
          position absolute
          width 16px
          height 16px
          line-height 16px
          text-align center
          background $c-pink
          border-radius 50%
          top -10px
          right -6px
          cursor pointer
    .clearfix:after
      display block
    .no-opera
      height 320px
  .clear-wrap
    &:after
     display block
     content ''
     clear both
  .label-box
    position relative
    float left
    margin 0 20px 10px 0
    input
      sing-inp()
    input:checked+span
      sing-sped()
    input+span
      sing-sp()
    input:checked+span
      &:after
        sing-af()
      &:before
        sing-be()
    input[disabled]
      cursor not-allowed
  .label-clear
    float left
    &:after
      display block
      content ''
      clear both
  .has-single
    border-top 1px solid #efeef3
    padding-top 16px
  .zhezhao
    display none
    position fixed
    top 0px
    left 0
    right 0
    bottom 0
    background $cf-gray0
    opacity .5
    z-index 6
  .hide-zhezhao
    display none
  .show-zhezhao
    display block
  .label-select-option
    max-width 500px
    height auto
    word-wrap break-word
    white-space normal
  .label-cursor
    cursor pointer
</style>
